package com.qfedu.controller;

import com.qfedu.entity.User;
import com.qfedu.service.UserService;
import com.qfedu.service.impl.UserServiceImpl;
import com.qfedu.utils.Base64Utils;
import com.qfedu.utils.BaseServlet;
import com.qfedu.utils.Constants;
import com.qfedu.utils.MD5Utils;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.security.PublicKey;
import java.sql.SQLException;

@WebServlet("/user.do")
public class UserServlet extends BaseServlet {
    private UserService userService = null;
    @Override
    public void init() throws ServletException {
        userService = new UserServiceImpl();
    }

    /**
     * 检查用户名是否存在
     * 返回 1 ：用户名已存在
     * 返回 0 ：用户名 不存在 可用
     * @param request
     * @param response
     * @return
     */
    public String checkUserName(HttpServletRequest request, HttpServletResponse response){
        String username = request.getParameter("username");
        try {
            User user = userService.findUserByUserName(username);
            if (user != null){
                return "1";
            }else {
                return "0";
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        request.setAttribute("msg","服务器发生异常");
        return Constants.FORWARD + "/message.jsp";
    }

    /**
     * 注册 用户  比较密码是否正确
     * @param request
     * @param response
     * @return
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public String register(HttpServletRequest request, HttpServletResponse response) throws InvocationTargetException, IllegalAccessException {
        User user = new User();
        BeanUtils.populate(user,request.getParameterMap());
        String upassword2 = request.getParameter("upassword2");
        if (! upassword2.equals(user.getUpassword())){
            request.setAttribute("registerMsg","两次密码不一致");
            return Constants.FORWARD + "/register.jsp";
        }
        try {
            boolean result = userService.registerUser(user);
            if (result){
                return Constants.FORWARD + "registerSuccess.jsp";
            }else {
                request.setAttribute("registerMsg","注册失败，请重新注册");
                return Constants.FORWARD + "/register.jsp";
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        request.setAttribute("msg","服务器发生异常");
        return Constants.FORWARD + "/message.jsp";
    }

    /**
     * 激活用户
     * @param request
     * @param response
     * @return
     */
    public String active(HttpServletRequest request, HttpServletResponse response){
        String code = request.getParameter("c");
        try {
            boolean result = userService.activeUserByCode(code);
            if (result){
                return Constants.FORWARD + "/login.jsp";
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        request.setAttribute("msg","服务器发生异常");
        return Constants.FORWARD + "/message.jsp";
    }

    /**
     * 输入用户名 密码 验证码 登录
     * @param request
     * @param response
     * @return
     */
    public String login(HttpServletRequest request, HttpServletResponse response){
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String code = request.getParameter("code");
        String auto = request.getParameter("auto");
        String sessionCode = (String) request.getSession().getAttribute("code");
        try {
            User user = userService.findUserByUserName(username);
            if (user != null){
                if (Constants.USER_ACTIVE.equals(user.getUstatus())){
                    if (MD5Utils.md5(password).equals(user.getUpassword())){
                        if (sessionCode.equalsIgnoreCase(code)) {
                            if ("on".equals(auto)){
                                String usernameAndPassword = username + Constants.FLAG + user.getUpassword();
                                Cookie cookie = new Cookie(Constants.AUTO_NAME, Base64Utils.encode(usernameAndPassword));
                                cookie.setPath("/");
                                cookie.setMaxAge(14 * 24 * 60 * 60);
                                response.addCookie(cookie);
                                request.getSession().setAttribute("loginUser",user);
                                return Constants.FORWARD + "/index.jsp";
                            }
                            // 将用户信息 存储在session 中 ，只要属于同一会话（session） 都共享loginUser

                        }else {
                            request.setAttribute("msg", "验证码错误");
                            return Constants.FORWARD +"/login.jsp";
                        }
                    }else {
                        request.setAttribute("msg", "密码错误");
                        return Constants.FORWARD +"/login.jsp";
                    }
                }else {
                    request.setAttribute("msg", "该用户未激活");
                    return Constants.FORWARD +"/login.jsp";
                }
            }else {
                request.setAttribute("msg", "该用户不存在");
                return Constants.FORWARD +"/login.jsp";
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        request.setAttribute("msg", "服务器发生异常");
        return Constants.FORWARD + "/message.jsp";
    }

    /**
     * 注销登录
     * @param request
     * @param response
     * @return
     */
    public String logOut(HttpServletRequest request, HttpServletResponse response){
        request.getSession().invalidate();
        return Constants.FORWARD + "/login.jsp";
    }
}
